<%@ page language="java" import="com.alibaba.fastjson.JSONArray" pageEncoding="UTF-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.interfaces.cese.duss.ceseutil.OcrUitl" %>
<%@ page import="javax.net.ssl.HttpsURLConnection" %>
<%@ page import="java.io.*" %>
<%@ page import="java.net.URL" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%
    try {
        String originPath="/home/weaver/ecology/interface/cese/ticket/";
        String fileName = request.getParameter( "fileName" );
        File file = new File(originPath);
        String path = Util.null2String( originPath+fileName );
        if(isExistFile(file,fileName)){
            out.println( "*********************************************<br>");
            out.println( "*****************发票ORC识别开始**********<br>");
            out.println( "*********************************************<br>");
            Map<String,String> resultMap = httpPost( path );
            JSONObject resultJson = JSONObject.parseObject(resultMap.get("result") );
            String code = resultMap.get("code");
            if("200".equals(code)){
                if (!"".equals( resultMap.get("result") )) {
                    JSONObject response1 = JSONObject.parseObject( resultJson.getString( "response" ) );
                    JSONObject data = JSONObject.parseObject( response1.getString( "data" ) );
                    JSONArray identifyResults = JSONArray.parseArray( data.getString( "identifyResults" ) );
                    for (int i = 0; i < identifyResults.size(); i++) {
                        JSONObject results = (JSONObject) identifyResults.get( i );
                        String category = results.getString( "category" );//发票类型
                        JSONObject details = JSONObject.parseObject( results.getString( "details" ) );//发票识别的具体信息
                        String invoiceType = details.getString( "invoiceType" );//发票类型
                        String newinvoiceType = OcrUitl.getOrcTicketType(category,invoiceType);//发票类型
                        String invoiceCode = Util.null2String(details.getString( "invoiceCode" ));//发票代码
                        String invoiceNum = details.getString( "invoiceNum" );//发票号码
                        String invoiceDate = OcrUitl.transInvoiceDate( details.getString( "invoiceDate" ) );
                        String totalAmount = details.getString( "totalAmount" );
                        String checkCode = details.getString( "checkCode" );
                        String subCheckCode = checkCode.length() >= 6 ? checkCode.substring( checkCode.length() - 6 ) : checkCode;
                        String purchaserRegisterNum = details.getString( "purchaserRegisterNum" );
                        out.println( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>发票类型：" + category+"<br>" );
                        out.println( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>发票明细信息：" + details+"<br>" );
                        out.println( "*********************************************<br>");
                        out.println( "*****************发票验真开始***************<br>");
                        out.println( "*********************************************<br>");
                        String invoiceType1 = OcrUitl.getYZTicketType(newinvoiceType);
                        out.println( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>获取发票验真参数:<br>" );
                        out.println( "===============[invoiceType]="+invoiceType1+";<br>" );
                        out.println( "===============[invoiceCode]="+invoiceCode+";<br>" );
                        out.println( "===============[invoiceNum]="+invoiceNum+";<br>" );
                        out.println( "===============[invoiceDate]="+invoiceDate+";<br>" );
                        out.println( "===============[totalAmount]="+totalAmount+";<br>" );
                        out.println( "===============[checkCode]="+subCheckCode+";<br>" );
                        out.println( "===============[TaxpayerIDNo]="+purchaserRegisterNum+";<br>" );
                        Map<String, Object> resultMap1 = invoicerecertify( invoiceType1, invoiceCode, invoiceNum, invoiceDate, totalAmount, checkCode, purchaserRegisterNum );
                        out.println( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>发票验真接口结果返回:<br>");
                        out.println( "===============接口返回验真状态="+resultMap1.get( "flag" )+"<br>");
                        out.println( "===============接口返回验真信息="+resultMap1.get( "msg" )+"<br>");
                    }
                } else {
                    out.print( "***********浪潮影像识别接口返回结果为空,请联系浪潮工作人员***********<br>" );
                }
            }else {
                out.print( "***********浪潮影像识别接口异常>>>>>>状态码："+code +"<<<<<<请联系浪潮工作人员<br>");
            }
        }else {
            out.println( "************上传发票不存在***************<br>");
            out.println( "************请检查发票文件是否存在或者发票名称是否正确***************<br>");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }


%>
<%!
    //发票ORC识别接口
    public static Map<String,String> httpPost(String path) {
        String result = "";
        Map<String,String> resultMap = new HashMap<>(  );
        try {
            File file = new File( path );
            URL url = new URL( "https://api.inspuronline.com/ai/ocr/v1/receipt/multiple" );
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            con.setDoOutput( true );
            con.setDoInput( true );
            con.setRequestMethod( "POST" );
            con.setUseCaches( false );
            con.setRequestProperty( "MediaType", "application/octet-stream" );
            con.setRequestProperty( "Content-Type", "application/octet-stream" );
            con.setRequestProperty( "X-API-Key", "52f19a5e-622f-ed63-1a23-2e0407ee1e2b" );
            OutputStream out = con.getOutputStream();
            //传入参数
            FileInputStream inputStream = new FileInputStream( file );
            byte[] data = new byte[2048];
            int len = 0;
            while ((len = inputStream.read( data )) != -1) {//将读取到的本地文件流读取到HttpsURLConnection,进行上传
                out.write( data, 0, len );
            }
            out.flush();
            inputStream.close();
            out.close();
            int code = con.getResponseCode(); //获取post请求返回状态
            resultMap.put("code",code+"");
            BufferedReader br = new BufferedReader( new InputStreamReader( con.getInputStream(), "UTF-8" ) );
            result = br.readLine();
            //获取请求的资源
            con.disconnect();//断开HttpsURLConnection连接
            resultMap.put("result",result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return resultMap;
    }
    //发票验真接口
    public static JSONObject getInvoiceValidate(String urlString, String API_KEY, JSONObject params) {
        Map<String, String> headers = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        headers.put( "MediaType", "application/octet-stream" );
        headers.put( "Content-Type", "application/json" );
        headers.put( "X-API-Key", API_KEY );
        jsonObject.put( "Data", params );
        String result = OcrUitl.httpPostRaw( urlString, jsonObject.toJSONString(), headers, "UTF-8" );
        JSONObject resultJson = JSONObject.parseObject( result );//发票识别的具体信息
        return resultJson;
    }

    //发票认证
    public static Map<String, Object> invoicerecertify(String invoiceType, String invoiceCode, String invoiceNum, String invoiceDate, String totalAmount, String checkCode, String purchaserRegisterNum) {
        String YZ_API_KEY = "2d71665b-9f03-4eae-b104-3a985709a8f0";
        String yz_url = "https://api.inspuronline.com/business/cn-vat-receipt/v2/invoice-check-info";
        System.out.println( "----------发票验真----------" );
        String msg = "";
        boolean flag;
        Map<String, Object> dataMap = new HashMap<>();
        JSONObject params = new JSONObject();
        params.put( "InvoiceType", invoiceType );//发票类型
        params.put( "InvoiceCode", invoiceCode );//发票代码
        params.put( "InvoiceNumber", invoiceNum );//发票号码
        params.put( "DateOfInvoice", invoiceDate );//开票日期
        params.put( "Amount", totalAmount );//未税金额
        String subCheckCode = checkCode.length() >= 6 ? checkCode.substring( checkCode.length() - 6 ) : checkCode;
        params.put( "CheckCode", subCheckCode );//校验码后六位
        params.put( "TaxpayerIDNo", purchaserRegisterNum );//税号
        System.out.println( "params=" + params );
        JSONObject returnJson = getInvoiceValidate( yz_url, YZ_API_KEY, params );
        System.out.println( "returnJson=" + returnJson );
        JSONObject ReturnInfo = JSONObject.parseObject( returnJson.getString( "ReturnInfo" ) );
        String Code = ReturnInfo.getString( "Code" );
        String Message = ReturnInfo.getString( "Message" );
        if ("0".equals( Code )) {//验真通过
            flag = true;
            msg = Message;
        } else {
            flag = false;
            msg = Message;
        }
        dataMap.put( "flag", flag );
        dataMap.put( "msg", msg );
        return dataMap;
    }
    //判断目标目录下是否存在某个文件
    public static boolean isExistFile(File destDirPath, String fileName) {
        if (!destDirPath.exists()) {
            destDirPath.mkdirs();
        }
        File[] files = destDirPath.listFiles();
        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isDirectory()) {
                    isExistFile(f, fileName);
                } else {
                    String name = f.getName();
                    if (name.equals(fileName)) {
                        return Boolean.TRUE;
                    }
                }
            }
        }
        return Boolean.FALSE;
    }
%>